package com.riteny.paymentgateway.swifypass.common;

import org.dom4j.Element;
import org.springframework.web.client.RestTemplate;

/**
 * @author Riteny
 * 2021/12/24  11:56
 */
public abstract class SwiftPassPaymentGatewayUtil {

    private static RestTemplate restTemplate = new RestTemplate();

    public static final String SWIFT_PASS_RESPONSE_SUCCESS = "0";


    /**
     * 對調用威富通接口的API 抽取的公用方法
     * 首先會對入參進行簽名，並將簽名值保存到sign節點中
     * <p>
     * 并在調用完成后對返回的參數結果進行驗簽
     *
     * @param paymentGatewayKey 支付密鑰
     * @param paymentGatewayUrl 回調地址
     * @param requestXml        請求參數
     * @return 返回XML
     */
    public static Element requestPaymentGatewayTemplate(String paymentGatewayKey, String paymentGatewayUrl, Element requestXml) {

        //step2 獲取簽名數據
        String sign = SwiftPassPaymentGatewaySha256Util.getSignStr(requestXml, paymentGatewayKey);

        //step3 將簽名字符串擺入請求參數中
        requestXml.addElement("sign").setText(sign);

        String responseStr = restTemplate.postForEntity(paymentGatewayUrl, requestXml.asXML(), String.class).getBody();

        return SwiftPassPaymentGatewaySha256Util.checkSignStrFromResponse(responseStr, paymentGatewayKey);
    }
}
